/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package org.karol.lx.agent;

import java.io.IOException;
import java.util.logging.Level;
import java.util.logging.Logger;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.params.BasicHttpParams;
import org.apache.http.params.HttpParams;
import org.apache.http.protocol.BasicHttpContext;
import org.apache.http.protocol.HttpContext;
import org.apache.http.util.EntityUtils;
import org.karol.lx.model.GradeRequest;

/**
 *
 * @author karol
 */
public class GraderBackgroundWorker implements Runnable {
    
    private GradeRequest mRequest;
    private HttpClient mClient;
    private HttpContext mContext;
    private GraderEventListener mListener = null;

    public GraderBackgroundWorker(GraderEventListener pListener , GradeRequest mRequest) {
        mListener = pListener;
        this.mRequest = mRequest;
        mClient = new DefaultHttpClient();
        mContext = new BasicHttpContext();
    }
    
    protected final void notifyGradingSuccess() {
        if (mListener != null)
            mListener.onGradingSuccess(mRequest);
    }
    
    protected final void notifyGradingFailed(Object pReason) {
        if (mListener != null)
            mListener.onGradingFailed(mRequest, pReason);
    }

    @Override
    public void run() {
        HttpPost tMethod = new HttpPost("http://localhost/lz/services/backend/grade?id=" + mRequest.id);
        //HttpParams tParam = new BasicHttpParams();
        //tParam.setIntParameter("id", mRequest.id);
        //tMethod.setParams(tParam);
        try {
            HttpResponse tResponse = mClient.execute(tMethod, mContext);
            HttpEntity tEntity = tResponse.getEntity();
            
            if (tResponse.getStatusLine().getStatusCode() == 200) { //Success
                notifyGradingSuccess();
            }
            else { //Failed
                notifyGradingFailed("HTTP response");
            }
        } catch (IOException ex) { //Failed
            Logger.getLogger(GraderBackgroundWorker.class.getName()).log(Level.SEVERE, null, ex);
            notifyGradingFailed(ex);
        }
    }
    
    public static void main(String[] args) {
        (new Thread(new GraderBackgroundWorker(null , null))).start();
    }
}
